package com.business.lgh.naocs.naming.core.pojo;

import com.business.lgh.nacos.api.naming.common.CommonParams;
import com.business.lgh.nacos.api.naming.common.ConstantValue;
import com.business.lgh.nacos.api.naming.pojo.Instance;
import com.business.lgh.nacos.core.utils.WebUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.pqc.math.linearalgebra.IntUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lgh
 * @version V1.0
 * @Package com.business.lgh.naocs.naming.core.pojo
 * 工厂Bean
 * @date 2020/6/23 3:36 下午
 */
public class InstanceWrapperFacotry {


    public static final String IP = "ip";
    public static final String PORT = "port";
    public static final String WEIGHT = "weight";
    public static final String ENABLED = "enabled";
    public static final String HEALTHY = "healthy";
    public static final String EPHEMERAL = "ephemeral";

    public static InstanceWrapper getInstance(HttpServletRequest req){

        Instance instance=new InstanceWrapper();
        //设置IP和端口
        instance.setIp(WebUtils.required(req,IP));
        instance.setPort(Integer.parseInt(WebUtils.required(req,PORT)));
        //设置命名空间
        instance.setNamespaceId(WebUtils.optional(req, CommonParams.NAMESPACE_ID, ConstantValue.DEFAULT_NAMESPACE_ID));
        //设置节点
        instance.setClusterName(WebUtils.optional(req, CommonParams.CLUSTER_NAME, StringUtils.EMPTY));
        //设置是否可接受请求及是否健康
        instance.setEnabled(BooleanUtils.toBoolean(WebUtils.optional(req, ENABLED,"true")));
        instance.setHealthy(BooleanUtils.toBoolean(WebUtils.optional(req,HEALTHY,"true")));
        //设置是否临时节点
        instance.setEphemeral(BooleanUtils.toBoolean(WebUtils.optional(req, EPHEMERAL,"true")));

        //设置服务名称
        instance.setServiceName( WebUtils.required(req, CommonParams.SERVICE_NAME));
        //生成唯一ID
        instance.setInstanceId(instance.generateInstanceId());
        //生成心跳时间
        ((InstanceWrapper)instance).setBeatTime(System.currentTimeMillis());

        return (InstanceWrapper)instance;
    }

}
